<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :max-height="maxHeight"
    :width="width"
    append-to-body
    class="payment-dialog"
  >
    <el-container>
      <el-aside class="aside">
        <el-scrollbar :max-height="maxHeight" class="pr-20px">
          <div
            class="payment-item"
            v-for="(item, index) in state.payMethods.items"
            @click="selectPayMent(index)"
            :key="index"
            :class="{ 'payment-item-active': nowPaymentIndex == index || item.payStatus }"
          >
            <el-image :src="item.icon" class="icon ml-10px" />
            <el-text class="custom-text-18 ml-10px!" truncated> {{ item.assetsTitle }}</el-text>
            <div class="virtual_san" v-if="item.payStatus"></div>
            <div class="virtual_dui custom-text-18" v-if="item.payStatus">✓</div>
          </div>
        </el-scrollbar>
      </el-aside>
      <el-main class="main pos-relative">
        <div class="meton-mask cursor-not-allowed z-1" v-if="!nowPayment.usable"></div>

        <el-row class="payment-info">
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(state.orderInfo.price.totalPrice) }}</div
              >
              <div class="custom-text-18">订单金额</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(state.payMethods.totalPayPrice) }}</div
              >
              <div class="custom-text-18">本次使用</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(noPaidPrice) }}</div
              >
              <div class="custom-text-18">待支付金额</div>
            </div>
          </el-col>
          <el-col
            :xs="24"
            :sm="24"
            :md="24"
            :lg="24"
            :xl="24"
            v-if="nowPayment.rebatePrice > 0 && nowPayment.payStatus"
          >
            <el-divider border-style="dashed" class="m-y-0px!" />

            <div class="text-center">
              <div class="custom-text-16">
                {{ nowPayment.assetsTitle }}优惠金额
                <span class="c-[var(--el-color-primary)]!"
                  >￥{{
                    nowPayment.usingDis ? fenToYuan(nowPayment.rebatePrice) : fenToYuan(0)
                  }}</span
                ></div
              >
            </div>
          </el-col>
          <el-col
            :xs="24"
            :sm="24"
            :md="24"
            :lg="24"
            :xl="24"
            v-if="nowPayment.duePrice > 0 && !nowPayment.payStatus"
          >
            <el-divider border-style="dashed" class="m-y-0px!" />

            <div class="text-center">
              <div class="custom-text-16">
                {{ nowPayment.assetsTitle }}优惠金额
                <span class="c-[var(--el-color-primary)]!"
                  >￥{{ nowPayment.usingDis ? fenToYuan(nowPayment.duePrice) : fenToYuan(0) }}</span
                ></div
              >
            </div>
          </el-col>
        </el-row>
        <div class="payment-operation">
          <div class="flex-1">
            <div class="mt-10px">
              <el-input
                v-model="nowPayment.usePayBalance"
                class="payment-input custom-text-44"
                :disabled="nowPayment.payStatus"
                ref="inputRef"
                :formatter="(value: any) => verifyNumberIntegerAndFloat(value)"
              >
                <template #prepend>
                  <div class="flex items-center">
                    <el-image :src="collection" class="collection-icon" />
                    <span class="custom-text-22 ml-5px"> 使用金额</span>
                  </div>
                </template>
              </el-input>
            </div>
            <div class="flex justify-between w-100% items-center mt-10px">
              <div class="custom-text-20" v-if="nowPaymenthds.classify == 'points'"
                >可用积分：{{ nowPayment.usableBalance }}
                <el-popover
                  placement="top"
                  effect="dark"
                  trigger="hover"
                  :content="`1积分抵扣${nowPayment.rebate}元`"
                >
                  <template #reference>
                    <Icon :icon="'ep:question-filled'" />
                  </template> </el-popover
              ></div>
              <div class="custom-text-20" v-else
                >可用余额：￥{{ fenToYuan(nowPayment.usableBalance) }}</div
              >
              <div class="flex">
                <el-button
                  type="primary"
                  v-if="nowPayment.usePayBalance != ''"
                  class="custom-text-18 mr-5px!"
                  @click="onHandleCancel"
                  link
                >
                  取消使用
                </el-button>
                <el-button
                  v-if="nowPayment.usePayBalance == ''"
                  type="primary"
                  class="custom-text-18 mr-5px!"
                  @click="handleAllPay"
                  link
                >
                  全额支付
                </el-button>
                <el-checkbox
                  class="!ml-5px"
                  v-model="nowPayment.usingDis"
                  :disabled="!nowPayment.usabledis"
                  @change="onUsingDisChange"
                  :border="false"
                >
                  <span class="custom-text-18">折扣</span>
                </el-checkbox>
              </div>
            </div>
          </div>
          <div class="flex items-center mt-10px justify-center">
            <DigitKeyboard
              ref="DigitKeyboardRef"
              @on-change="onInputChange"
              @on-confirm="onConfirm"
              @on-cancel="onHandleCancel"
              :disabled="nowPayment.payStatus"
              :input="nowPayment.usePayBalance"
            />
          </div>
        </div>
      </el-main>
    </el-container>
    <template #footer>
      <el-button @click="close" plain type="primary"> 卡类支付,确认提交</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
// 储值卡使用弹窗
import { defineAsyncComponent, ref } from 'vue'
import collection from '@/assets/svgs/collection.svg'

import { fenToYuan, yuanToFen } from '@/utils'

const DigitKeyboard = defineAsyncComponent(() => import('./digitKeyBoard.vue'))
import { propTypes } from '@/utils/propTypes'
const props = defineProps({
  orderInfo: propTypes.object, //订单信息
  paymentMap: propTypes.array
})
// 检测支付环境
const state = reactive({
  orderInfo: computed(() => {
    return props.orderInfo
  }), // 支付单信息
  payMethods: computed(() => {
    return props.paymentMap.find((ele: any) => {
      return ele.classify == nowPaymenthds.value.classify
    })
  }) as any, // 可选的支付方式
  payment: '', // 选中的支付方式
  payOrderList: [] as any, //当前支付方式的支付流水号
  activeName: '' //当前选中的支付方式
})

const nowPaymenthds = ref() //当前使用的资产

const DigitKeyboardRef = ref()
const onInputChange = (input: any) => {
  nowPayment.value.usePayBalance = input
} //输入发生变化时
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('选择资产') // 弹窗的标题
const width = ref('715px') //宽度
const maxHeight = ref('545px')
// 选择支付方式
const emit = defineEmits(['handleUsePaymentPay'])

// 监听支付方式的变化
watch(
  () => props.paymentMap,
  () => {
    if (nowPaymentIndex.value == undefined) {
      return
    }

    nowPayment.value = state.payMethods.items[nowPaymentIndex.value]
    if (nowPayment.value.payStatus) {
      nowPayment.value.usePayBalance = fenToYuan(nowPayment.value.paybalance)
    } else {
      nowPayment.value.usePayBalance = ''
    }
    setKeyBoardLayout()
  }
)
const nowPayment = ref<any>({})
const nowPaymentIndex = ref<any>() //当前支付方式的下标
const inputRef = ref()
const selectPayMent = (index: any) => {
  nowPaymentIndex.value = index
  let item = state.payMethods.items[nowPaymentIndex.value]
  if (!item.usable) {
    message.error('该支付方式不可用')
  }
  nowPayment.value = item
  nowPayment.value.usingDis = nowPayment.value.usabledis
  if (item.payStatus) {
    nowPayment.value.usePayBalance = fenToYuan(nowPayment.value.paybalance)
  } else {
    nowPayment.value.usePayBalance = ''
  }
  setKeyBoardLayout()
}
const onHandleCancel = () => {
  let item = state.payMethods.items[nowPaymentIndex.value]
  item.payStatus = false

  emit('handleUsePaymentPay', item, nowPaymenthds.value.classify)
}
const setKeyBoardLayout = () => {
  if (nowPayment.value.payStatus) {
    setTimeout(() => {
      DigitKeyboardRef.value.setKeyBoardLayout('cancel')
    }, 100)
  } else {
    setTimeout(() => {
      DigitKeyboardRef.value.setKeyBoardLayout('default')
    }, 100)
  }
}
/** 打开弹窗 */

const open = async (payMethods: any) => {
  dialogVisible.value = true
  nowPaymenthds.value = payMethods
  await setNowPayment()
}
const setNowPayment = () => {
  let selectPayMentIndexs = [] as any
  state.payMethods.items.forEach((element, index) => {
    if (element.payStatus) {
      selectPayMentIndexs.push(index)
    }
  })
  console.log(selectPayMentIndexs)

  if (selectPayMentIndexs.length == 0) {
    nowPayment.value = {}
    // selectPayMent(0)
  } else {
    nowPaymentIndex.value = selectPayMentIndexs[0]
    nowPayment.value = state.payMethods.items[nowPaymentIndex.value]
    state.activeName = nowPayment.value.assetsTitle
    nowPayment.value.usePayBalance = fenToYuan(nowPayment.value.paybalance)
  }
} //设置当前选中的支付方式

const handleAllPay = () => {
  // 如果可用余额大于待支付金额 支付金额就是待支付金额
  if (noPaidPrice.value < nowPayment.value!.usableBalance) {
    nowPayment.value.usePayBalance = fenToYuan(noPaidPrice.value)
  } else {
    nowPayment.value.usePayBalance = fenToYuan(nowPayment.value!.usableBalance)
  }
  return
  // onConfirm()
}
// 待支付金额
const noPaidPrice = computed(() => {
  if (
    state.orderInfo.price.payPrice &&
    !isEmpty(nowPayment.value.duePrice) &&
    nowPayment.value.usingDis
  ) {
    return state.orderInfo.price.payPrice - nowPayment.value.duePrice
  } else if (
    state.orderInfo.price.payPrice &&
    !isEmpty(nowPayment.value.duePrice) &&
    !nowPayment.value.usingDis
  ) {
    return state.orderInfo.price.payPrice
  } else {
    return 0
  }
})
const close = async () => {
  dialogVisible.value = false
}

defineExpose({ open, close }) // 提供 open 方法，用于打开弹窗

const message = useMessage() // 消息弹窗
import { verifyNumberIntegerAndFloat } from '@/utils/formatter'
import { isEmpty } from '@/utils/is'
/** 购物车信息 */

const onUsingDisChange = () => {
  console.log(nowPayment.value)
  if (nowPayment.value.usePayBalance > 0) {
    nowPayment.value.payStatus = true

    emit('handleUsePaymentPay', nowPayment.value, nowPaymenthds.value.classify)
  }
}
const onConfirm = () => {
  if (!nowPayment.value.usePayBalance) {
    message.error('使用金额不能为空')
    return
  }

  nowPayment.value.paybalance = yuanToFen(nowPayment.value.usePayBalance)

  if (Number(nowPayment.value.paybalance) <= 0) {
    message.error('使用金额必须大于0')
    return
  }
  if (Number(nowPayment.value.paybalance) > Number(nowPayment.value.usableBalance)) {
    message.error('使用金额不得大于可用金额')
    return
  }
  nowPayment.value.payStatus = true
  emit('handleUsePaymentPay', nowPayment.value, nowPaymenthds.value.classify)
} //确认当前支付方式
</script>
<style lang="scss">
.payment-dialog {
  padding-bottom: 10px;
  .#{$elNamespace}-overlay-dialog {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .#{$elNamespace}-dialog {
    margin: 0 !important;

    &__header {
      // height: 54px;
      padding: 0;
      margin-right: 0 !important;
      border-bottom: 1px solid var(--el-border-color);
    }

    &__body {
      padding: 10px 0 !important;
    }

    &__footer {
      border-top: 1px solid var(--el-border-color);
      padding-top: 10px;
    }

    &__headerbtn {
      top: 0;
    }
  }
}
</style>
<style lang="scss" scoped>
:deep(.el-input.is-disabled .el-input__wrapper) {
  background: transparent !important;
}
.aside {
  width: 210px;
}

.main {
  width: 470px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

:deep(.el-main) {
  --el-main-padding: 0px !important;
  width: 470px;
}

// .payment-item {
//   width: 190px;
//   height: 70px;
//   background: url('@/assets/imgs/payCashier/paymentBg.png') center no-repeat;
//   background-size: 100% 100%;
//   cursor: pointer;
//   display: flex;
//   align-items: center;
//   margin-bottom: 10px;
//   .icon {
//     width: 24px;
//     height: 24px;
//   }

//   .virtual_san {
//     display: none;
//   }

//   .virtual_dui {
//     display: none;
//   }

//   &-active {
//     background: url('@/assets/imgs/payCashier/paymentActive.png') center no-repeat;
//     background-size: 100% 100%;
//     position: relative;

//     .virtual_san {
//       display: block;
//       position: absolute;
//       bottom: 0;
//       right: 0;
//       width: 0;
//       height: 0;
//       border-bottom: 35px solid var(--el-color-primary);
//       border-left: 35px solid transparent;
//       border-bottom-right-radius: 5px;
//     }

//     .virtual_dui {
//       display: block;

//       position: absolute;
//       bottom: -2px;
//       right: 5px;
//       color: #fff;
//       font-family: system-ui;
//     }
//   }
// }
// .payment-info {
//   width: 470px;
//   height: 85px;
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
//   align-items: center;
//   background-color: var(--app-content-bg-color) !important;
//   border-radius: 5px;

//   &-item {
//     width: 117.5px;
//     text-align: center;
//   }
// }

// .dark .payment-info {
//   width: 470px;
//   height: 85px;
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
//   align-items: center;
//   background-color: var(--el-bg-color-overlay) !important;
//   border-radius: 5px;

//   &-item {
//     width: 117.5px;
//     text-align: center;
//   }
// }
// .payment-operation {
//   flex: 1;
//   display: flex;
//   flex-direction: column;
//   justify-content: space-between;
// }
.payment-input {
  width: 470px;

  height: 60px;

  :deep(.el-input-group__prepend) {
    background: var(--el-color-primary);
    color: #fff;
    padding: 0 10px;
    box-shadow: none;
  }

  :deep(.el-input__inner) {
    --el-input-inner-height: 48px;
  }
  :deep(.el-input-group__append) {
    background: var(--el-color-primary);
    color: #fff;
    padding: 0 10px;
    box-shadow: none;
  }
}

:deep(.el-divider--horizontal) {
  margin: 20px 0 13px 0;
}

.collection-icon {
  width: 24px;
  height: 24px;
}
</style>
